package com.cyzy.util;

import com.cyzy.config.MinioConfig;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class MinioUtil {
    private static final Logger log = LoggerFactory.getLogger(MinioUtil.class);
    private final MinioClient minioClient;
    private final String bucketName;

    @Autowired
    public MinioUtil(MinioClient minioClient, MinioConfig minioConfig) {
        this.minioClient = minioClient;
        this.bucketName = minioConfig.getBucketName();

        try {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                log.info("MinIO存储桶不存在，已创建：" + bucketName);
            } else {
                log.info("MinIO存储桶已存在：" + bucketName);
            }
        } catch (Exception e) {
            log.info("MinIO存储桶初始化失败：" + e.getMessage());
            throw new RuntimeException("MinIO初始化失败", e);
        }
        log.info("MinioUtil初始化完成，存储桶：" + bucketName);
    }

    /**
     * 批量上传文件到MinIO
     * @param fileList 待上传的文件列表（非空）
     * @return 所有文件的访问URL列表
     * @throws IOException 上传失败时抛出
     */
    public ArrayList<String> batchUploadFiles(ArrayList<MultipartFile> fileList) throws IOException {
        if (fileList == null || fileList.isEmpty()) {
            throw new IOException("批量上传的文件列表为空");
        }

        ArrayList<String> fileUrls = new ArrayList<>();
        for (MultipartFile file : fileList) {
            String fileUrl = uploadMultipartFile(file);
            fileUrls.add(fileUrl);
        }

        return fileUrls;
    }

    /**
     * 上传单个文件到MinIO
     * @param file 待上传的文件
     * @return 文件的访问URL
     * @throws IOException 上传失败时抛出
     */
    public String uploadMultipartFile(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new IOException("上传的文件为空");
        }

        try (InputStream inputStream = file.getInputStream()) {
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

            log.info("文件[{}]生成唯一名称：{}", originalFilename, uniqueFileName);

            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(uniqueFileName)
                            .contentType(file.getContentType())
                            .stream(inputStream, file.getSize(), -1)
                            .build()
            );

            log.info("文件[{}]上传MinIO成功", uniqueFileName);

            String fileUrl = "http://123.60.66.194:9000/" + bucketName + "/" + uniqueFileName;
            log.info("文件访问URL：{}", fileUrl);

            return fileUrl;
        } catch (MinioException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.info("MinIO操作失败：" + e.getMessage());
            throw new IOException("MinIO上传失败", e);
        }
    }
}